package com.app.controller.backstage;

//import com.app.conf.RedisService;

import com.app.conf.RedisService;
import com.app.model.AdminUserModel;
import com.app.service.AdminUserService;
import com.app.util.AESTool;
import com.app.util.RandomValidateCodeUtil;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.AdminUserVo;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@RestController
@Controller
@Slf4j
public class AdminUserController {
    @Autowired
    private Producer captchaProducer = null;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private RedisService redisService;

    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        HttpSession session = request.getSession();
//        response.setDateHeader("Expires", 0);
//        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
//        response.setHeader("Pragma", "no-cache");
//        response.setContentType("image/jpeg");
//        //生成验证码
//        String capText = captchaProducer.createText();
//        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
//        //向客户端写出
//        BufferedImage bi = captchaProducer.createImage(capText);
//        redisService.setStringKey(capText, capText);
//        redisService.setExpire(capText,60, TimeUnit.SECONDS);
//        ServletOutputStream out = response.getOutputStream();
//        ImageIO.write(bi, "jpg", out);
//        try {
//            out.flush();
//        } finally {
//            out.close();
//        }
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();


            //输出验证码图片方法
            randomValidateCode.getRandcode(request, response);
        } catch (Exception e) {
            log.error("获取验证码失败>>>>", e);
        }
    }


    public boolean checkVerify(String verifyInput, HttpSession session) {
        try {
            verifyInput = verifyInput.toLowerCase();
            String random = (String) redisService.getStringKey(verifyInput);
            if (random == null) {
                return false;
            }
        } catch (Exception e) {
            log.error("验证码校验失败", e);
            return false;
        }
        redisService.deleteKey(verifyInput);
        return true;
    }

    public static void main(String[] args) {
//        System.out.println(AESTool.dealAESDecrypt("11984346E0B72CF6471C50BD19B0F1FC", "hwsc_pass"));
        System.out.println(AESTool.dealAESEncrypt("bank_account", "hwsc_pass"));
    }

    /**
     * 后台登录
     */

    @PostMapping("/userLogin")
    public Result<Object> userLogin(@RequestParam("userName") String userName,
                                    @RequestParam("password") String passWord,
                                    @RequestParam("code") String code,
                                    HttpSession session) {

        String asePassWord = AESTool.dealAESEncrypt(passWord, "hwsc_pass");
//        String asePassWord = "11984346E0B72CF6471C50BD19B0F1FC";
//        if (redisService.getStringKey(code) == null) {
//            return Result.error(500, "验证码错误");
//        } else {
//            redisService.deleteKey(code);
//        }
        if (!this.checkVerify(code, session)) {
            return Result.error(500, "验证码错误");
        }
        AdminUserModel user = adminUserService.getUserByUserName(userName, asePassWord);
        if (user == null) {
            return Result.error(500, "用户名或密码错误");
        }
        String token = TokenUtils.sign(String.valueOf(user.getId()));
        AdminUserVo vo = new AdminUserVo();
        vo.setUser(user);
        vo.setToken(token);
        return Result.success(vo);
    }



    /**
     * 后台修改密码
     */
    @PostMapping("/updatePassWord")
    public Result<Object> userLogin(@RequestParam("pastPassWord") String pastPassWord,
                                    @RequestParam("newPassWord") String newPassWord,
                                    HttpServletRequest request
                                    ) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String asePassWord = AESTool.dealAESEncrypt(pastPassWord, "hwsc_pass");
        String newAsePassWord = AESTool.dealAESEncrypt(newPassWord, "hwsc_pass");
        if(!asePassWord.equals(user.getPassWord()))
        {
            return Result.error(500,"旧密码错误");
        } else if (newAsePassWord.equals(user.getPassWord())) {

            return Result.error(500,"新密码不能与旧密码一致");
        } else{
            user.setPassWord(AESTool.dealAESEncrypt(newPassWord, "hwsc_pass"));
            adminUserService.update(user);
            return Result.success("修改成功");
        }
    }
}
